package com.li.network.socket.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author li
 * @date 2023/6/14 14:08
 */
public class UDPClient {
    public static void main(String[] args) throws IOException {
        int port = 8066;

        //作为客户端，端口不重要。此处不填，由 OS 自动分配一个目前没有被使用的port
        try (DatagramSocket socket = new DatagramSocket()) {
            //发送数据
            InetAddress address = InetAddress.getByName("127.0.0.1");
            byte[] data = "Hello I'm Li".getBytes();
            DatagramPacket packet = new DatagramPacket(data, data.length, address, port);
            socket.send(packet);

            //接收数据
            byte[] data1 = new byte[1024];
            DatagramPacket packet1 = new DatagramPacket(data1, data1.length);
            socket.receive(packet1);
            String reply = new String(data1, 0, packet1.getLength());
            System.out.println("客户端接收：" + reply);
        }
    }
}
